package com.weilai.service.serviceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.dao.FollowersDao;
import com.weilai.dao.PostsDao;
import com.weilai.dao.ThoughtDao;
import com.weilai.dao.UserDao;
import com.weilai.domain.Follows;
import com.weilai.domain.Posts;
import com.weilai.domain.Thought;
import com.weilai.domain.User;
import com.weilai.service.FollowersService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class FollowersServiceImpl implements FollowersService {

    @Autowired
    private FollowersDao followersDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private PostsDao postsDao;
    @Autowired
    private ThoughtDao thoughtDao;

    @Override
    public boolean isFan(int myId, int userId) {
        Follows fan = followersDao.isFan(myId, userId);
        if(fan==null){
            return false;
        }else{
            return true;
        }

    }

    @Override
    public boolean isFollowing(int myId, int userId) {
        Follows following = followersDao.isFollowing(myId, userId);
        return following != null;
    }

    @Override
    public List<User> selectFansById(int id) {
        // 检查查询结果是否为 null
        List<Follows> follows = followersDao.selectFansById(id);


        if (follows == null) {
            return new ArrayList<>();
        }

        List<User> users = new ArrayList<>();
        for (Follows follow : follows) {
            // 检查当前元素是否为 null
            if (follow != null) {
                int followerId = follow.getFollowerId();
                User user = userDao.getById(followerId);
                if (user != null) {
                    users.add(user);
                }
            }
        }
        return users;
    }


    @Override
    public List<User> selectFollowingsById(int id) {
        // 检查查询结果是否为 null
        List<Follows> followings = followersDao.selectFollowingsById(id);
        if (followings == null) {
            return new ArrayList<>();
        }

            List<User>  users=new ArrayList<>();
        for(Follows following:followings){
            if (following != null) {
                int followingId = following.getFollowingId();
                User user = userDao.getById(followingId);
                if (user != null) {
                    users.add(user);
                }
            }
        }
        return users;
    }

    @Transactional
    @Override
    public void followOthers(int followId,int followingId){
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String currentTime = now.format(formatter);
        try {
            followersDao.followOthers(followId, followingId, currentTime);
            followersDao.updateFollowOthersByFollowingId(followingId);
            followersDao.updateFollowOthersBySubscription(followId);
        }catch (BusinessException ex){
            throw new BusinessException(Code.PROJECT_BUSINESS_ERROR,"当前无法关注,请稍后再试");
        }
    }

    @Override
    public List<List<Posts>> postsFromMyFollowings(int followerId){

        List<Follows> followings = followersDao.selectFollowingsById(followerId);
        List<List<Posts>> allPosts=new ArrayList<>();
        for(Follows following:followings){
            int followingId =  following.getFollowingId();
            User user = userDao.getById(followingId);
            Integer id = user.getId();
            List<Posts> posts = postsDao.selectByUserId(id);
            allPosts.add(posts);
        }
        return allPosts;
    }

    @Override
    public List<List<Thought>> thoughtsFromMyFollowings(int followerId){
        List<Follows> followings = followersDao.selectFollowingsById(followerId);
        List<User> users=new ArrayList<>();
        List<List<Thought>> allThoughts=new ArrayList<>();
        for(Follows following:followings){
            int followingId =  following.getFollowingId();
            User user = userDao.getById(followerId);
            Integer id = user.getId();
            List<Thought> thoughts = thoughtDao.selectByUserId(id);
            allThoughts.add(thoughts);
        }
        return allThoughts;
    }

    // 按 userid 删除关注信息
    @Override
    public void deleteUserById(int userId){
        try {
            followersDao.deleteUserById(userId);
        } catch (Exception e) {
            throw new BusinessException(Code.SYSTEM_DB_ERROR, "按id删除用户信息时数据库出错");
        }
    }

    @Transactional
    @Override
    public void cancelFollow(int followerId, int followingId) {
        try {
            followersDao.cancelFollow(followerId,followingId);
            followersDao.cancelFollowOthersBySubscription(followerId);
            followersDao.cancelFollowOthersByFollowingId(followingId);
        }catch (BusinessException ex){
            throw new BusinessException(Code.PROJECT_BUSINESS_ERROR,"当前无法取消关注,请稍后再试");
        }
    }

    @Override
    public PageInfo<Posts> postsFromMyFollowingsWithPaging(int followerId, int pageNum, int pageSize) {
        List<Follows> followings = followersDao.selectFollowingsById(followerId);
        List<Integer> followingsIds=new ArrayList<>();
        for(Follows follows:followings){
           followingsIds.add(follows.getFollowingId());
       }
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<Posts> pageInfo = new PageInfo<>(postsDao.findPostsByUserIds(followingsIds));
        return pageInfo;
    }
}